<template>
  <div class="reports-container">
    <div class="reports-header">
      <h1>财务报表</h1>
      <div class="header-controls">
        <Select v-model:value="reportType" placeholder="选择报表类型" class="report-type-select">
          <SelectOption value="monthly">月度报表</SelectOption>
          <SelectOption value="category">分类报表</SelectOption>
          <SelectOption value="trend">趋势分析</SelectOption>
        </Select>
        
        <Select v-model:value="selectedPeriod" placeholder="选择时间段" class="period-select">
          <SelectOption value="current-month">本月</SelectOption>
          <SelectOption value="last-month">上月</SelectOption>
          <SelectOption value="last-3-months">近3个月</SelectOption>
          <SelectOption value="last-6-months">近6个月</SelectOption>
          <SelectOption value="current-year">今年</SelectOption>
        </Select>
      </div>
    </div>
    
    <!-- 报表内容 -->
    <div class="reports-content">
      <!-- 财务概览 -->
      <div class="overview-section">
        <div class="overview-card">
          <div class="overview-title">收入总计</div>
          <div class="overview-value income">
            {{ formatCurrency(overviewData.income) }}
          </div>
          <div class="overview-change" :class="overviewData.incomeChange >= 0 ? 'positive' : 'negative'">
            {{ overviewData.incomeChange >= 0 ? '+' : '' }}{{ overviewData.incomeChange }}%
          </div>
        </div>
        
        <div class="overview-card">
          <div class="overview-title">支出总计</div>
          <div class="overview-value expense">
            {{ formatCurrency(overviewData.expense) }}
          </div>
          <div class="overview-change" :class="overviewData.expenseChange >= 0 ? 'positive' : 'negative'">
            {{ overviewData.expenseChange >= 0 ? '+' : '' }}{{ overviewData.expenseChange }}%
          </div>
        </div>
        
        <div class="overview-card">
          <div class="overview-title">结余</div>
          <div class="overview-value balance">
            {{ formatCurrency(overviewData.balance) }}
          </div>
          <div class="overview-change" :class="overviewData.balanceChange >= 0 ? 'positive' : 'negative'">
            {{ overviewData.balanceChange >= 0 ? '+' : '' }}{{ overviewData.balanceChange }}%
          </div>
        </div>
        
        <div class="overview-card">
          <div class="overview-title">收支比</div>
          <div class="overview-value ratio">
            {{ overviewData.ratio }}%
          </div>
          <div class="overview-hint">支出/收入</div>
        </div>
      </div>
      
      <!-- 图表区域 -->
    <div class="charts-section">
      <!-- 月度报表 -->
      <div v-if="reportType === 'monthly'" class="chart-grid">
        <div class="chart-card">
          <h3>月度收支趋势</h3>
          <div class="chart-container">
            <div class="chart-placeholder">月度收支柱状图</div>
          </div>
        </div>
        
        <div class="chart-card">
          <h3>月度收支占比</h3>
          <div class="chart-container">
            <div class="chart-placeholder">月度收支饼图</div>
          </div>
        </div>
      </div>
      
      <!-- 分类报表 -->
      <div v-else-if="reportType === 'category'" class="chart-grid">
        <div class="chart-card">
          <h3>支出分类分析</h3>
          <div class="chart-container">
            <div class="chart-placeholder">支出分类饼图</div>
          </div>
        </div>
        
        <div class="chart-card">
          <h3>分类支出排行</h3>
          <div class="chart-container">
            <div class="chart-placeholder">分类支出柱状图</div>
          </div>
        </div>
      </div>
      
      <!-- 趋势分析 -->
      <div v-else-if="reportType === 'trend'" class="chart-grid">
        <div class="chart-card full-width">
          <h3>收支趋势分析</h3>
          <div class="chart-container">
            <div class="chart-placeholder">收支趋势折线图</div>
          </div>
        </div>
        
        <div class="chart-card">
          <h3>支出变化趋势</h3>
          <div class="chart-container">
            <div class="chart-placeholder">支出趋势折线图</div>
          </div>
        </div>
        
        <div class="chart-card">
          <h3>收入变化趋势</h3>
          <div class="chart-container">
            <div class="chart-placeholder">收入趋势折线图</div>
          </div>
        </div>
      </div>
    </div>
      
      <!-- 详细数据表格 -->
      <div class="details-section">
        <div class="section-header">
          <h3>详细数据</h3>
        </div>
        
        <Table 
          :columns="detailColumns" 
          :data="detailData"
          :pagination="detailPagination"
          class="details-table"
        >
          <template #cell(amount)="{ record }">
            <span :class="record.type === 'income' ? 'income' : 'expense'">
              {{ record.type === 'income' ? '+' : '-' }}{{ formatCurrency(record.amount) }}
            </span>
          </template>
          <template #cell(percentage)="{ record }">
            <span>{{ record.percentage }}%</span>
          </template>
        </Table>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue';
import { useFinanceStore } from '../store/finance';
import {
  Table,
  Select
} from '@arco-design/web-vue';

const financeStore = useFinanceStore();

// 状态管理
const reportType = ref<'monthly' | 'category' | 'trend'>('monthly');
const selectedPeriod = ref('current-month');

// 计算属性：获取当前选择时间段的交易数据
const periodTransactions = computed(() => {
  const now = new Date();
  let startDate: Date;
  
  switch (selectedPeriod.value) {
    case 'current-month':
      startDate = new Date(now.getFullYear(), now.getMonth(), 1);
      break;
    case 'last-month':
      startDate = new Date(now.getFullYear(), now.getMonth() - 1, 1);
      now.setDate(0); // 上个月的最后一天
      break;
    case 'last-3-months':
      startDate = new Date(now.getFullYear(), now.getMonth() - 2, 1);
      break;
    case 'last-6-months':
      startDate = new Date(now.getFullYear(), now.getMonth() - 5, 1);
      break;
    case 'current-year':
      startDate = new Date(now.getFullYear(), 0, 1);
      break;
    default:
      startDate = new Date(now.getFullYear(), now.getMonth(), 1);
  }
  
  return financeStore.transactions.filter(t => {
    const transactionDate = new Date(t.date);
    return transactionDate >= startDate && transactionDate <= now;
  });
});

// 计算属性：获取上期数据
const previousPeriodData = computed(() => {
  const now = new Date();
  let startDate: Date;
  let endDate: Date;
  
  switch (selectedPeriod.value) {
    case 'current-month':
      startDate = new Date(now.getFullYear(), now.getMonth() - 1, 1);
      endDate = new Date(now.getFullYear(), now.getMonth(), 0);
      break;
    case 'last-month':
      startDate = new Date(now.getFullYear(), now.getMonth() - 2, 1);
      endDate = new Date(now.getFullYear(), now.getMonth() - 1, 0);
      break;
    case 'last-3-months':
      startDate = new Date(now.getFullYear(), now.getMonth() - 5, 1);
      endDate = new Date(now.getFullYear(), now.getMonth() - 2, 0);
      break;
    case 'last-6-months':
      startDate = new Date(now.getFullYear(), now.getMonth() - 11, 1);
      endDate = new Date(now.getFullYear(), now.getMonth() - 5, 0);
      break;
    case 'current-year':
      startDate = new Date(now.getFullYear() - 1, 0, 1);
      endDate = new Date(now.getFullYear(), 0, 0);
      break;
    default:
      startDate = new Date(now.getFullYear(), now.getMonth() - 1, 1);
      endDate = new Date(now.getFullYear(), now.getMonth(), 0);
  }
  
  const transactions = financeStore.transactions.filter(t => {
    const transactionDate = new Date(t.date);
    return transactionDate >= startDate && transactionDate <= endDate;
  });
  
  const income = transactions
    .filter(t => t.type === 'income')
    .reduce((sum, t) => sum + t.amount, 0);
  
  const expense = transactions
    .filter(t => t.type === 'expense')
    .reduce((sum, t) => sum + t.amount, 0);
  
  return {
    income,
    expense,
    balance: income - expense
  };
});

// 计算属性：概览数据
const overviewData = computed(() => {
  const income = periodTransactions.value
    .filter(t => t.type === 'income')
    .reduce((sum, t) => sum + t.amount, 0);
  
  const expense = periodTransactions.value
    .filter(t => t.type === 'expense')
    .reduce((sum, t) => sum + t.amount, 0);
  
  const balance = income - expense;
  const ratio = income > 0 ? Math.round((expense / income) * 100) : 0;
  
  // 计算同比变化
  const { income: prevIncome, expense: prevExpense, balance: prevBalance } = previousPeriodData.value;
  const incomeChange = prevIncome > 0 ? Math.round(((income - prevIncome) / prevIncome) * 100) : 0;
  const expenseChange = prevExpense > 0 ? Math.round(((expense - prevExpense) / prevExpense) * 100) : 0;
  const balanceChange = prevBalance > 0 ? Math.round(((balance - prevBalance) / prevBalance) * 100) : 0;
  
  return {
    income,
    expense,
    balance,
    ratio,
    incomeChange,
    expenseChange,
    balanceChange
  };
});

// 方法：格式化货币
const formatCurrency = (amount: number): string => {
  return '¥' + amount.toLocaleString('zh-CN', {
    minimumFractionDigits: 2,
    maximumFractionDigits: 2
  });
};

// 获取分类名称
const getCategoryName = (categoryId: string): string => {
  const category = financeStore.categories.find(cat => cat.id === categoryId);
  return category ? category.name : '未知分类';
};

// 月度报表数据
const monthlyBarData = computed(() => {
  // 按月份分组数据
  const monthlyData: Record<string, { income: number; expense: number }> = {};
  
  periodTransactions.value.forEach(t => {
    const date = new Date(t.date);
    const monthKey = `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}`;
    
    if (!monthlyData[monthKey]) {
      monthlyData[monthKey] = { income: 0, expense: 0 };
    }
    
    if (t.type === 'income') {
      monthlyData[monthKey].income += t.amount;
    } else {
      monthlyData[monthKey].expense += t.amount;
    }
  });
  
  // 转换为图表数据格式
  const months = Object.keys(monthlyData).sort();
  return {
    columns: ['月份', '收入', '支出'],
    rows: months.map(month => ({
      '月份': month,
      '收入': monthlyData[month].income,
      '支出': monthlyData[month].expense
    }))
  };
});

const monthlyBarOptions = {
  legend: {
    position: 'top'
  },
  xAxis: {
    label: {
      autoHide: true
    }
  },
  yAxis: {
    label: {
      formatter: (v: number) => '¥' + v
    }
  },
  tooltip: {
    formatter: (datum: any) => {
      return {
        name: datum.name,
        value: '¥' + datum.value.toLocaleString('zh-CN')
      };
    }
  }
};

const monthlyPieData = computed(() => {
  const income = periodTransactions.value
    .filter(t => t.type === 'income')
    .reduce((sum, t) => sum + t.amount, 0);
  
  const expense = periodTransactions.value
    .filter(t => t.type === 'expense')
    .reduce((sum, t) => sum + t.amount, 0);
  
  return {
    columns: ['类型', '金额'],
    rows: [
      { '类型': '收入', '金额': income },
      { '类型': '支出', '金额': expense }
    ]
  };
});

const monthlyPieOptions = {
  legend: {
    position: 'right'
  },
  tooltip: {
    formatter: (datum: any) => {
      const total = datum.points.reduce((sum: number, point: any) => sum + point.value, 0);
      const percentage = ((datum.value / total) * 100).toFixed(1);
      return {
        name: datum.name,
        value: `¥${datum.value.toLocaleString('zh-CN')} (${percentage}%)`
      };
    }
  }
};

// 分类报表数据
const categoryPieData = computed(() => {
  const expenseByCategory: Record<string, number> = {};
  
  periodTransactions.value
    .filter(t => t.type === 'expense')
    .forEach(t => {
      if (!expenseByCategory[t.category]) {
        expenseByCategory[t.category] = 0;
      }
      expenseByCategory[t.category] += t.amount;
    });
  
  return {
    columns: ['分类', '金额'],
    rows: Object.entries(expenseByCategory).map(([categoryId, amount]) => ({
      '分类': getCategoryName(categoryId),
      '金额': amount
    }))
  };
});

const categoryPieOptions = {
  legend: {
    position: 'right'
  },
  tooltip: {
    formatter: (datum: any) => {
      const total = datum.points.reduce((sum: number, point: any) => sum + point.value, 0);
      const percentage = ((datum.value / total) * 100).toFixed(1);
      return {
        name: datum.name,
        value: `¥${datum.value.toLocaleString('zh-CN')} (${percentage}%)`
      };
    }
  }
};

const categoryBarData = computed(() => {
  const expenseByCategory: Record<string, number> = {};
  
  periodTransactions.value
    .filter(t => t.type === 'expense')
    .forEach(t => {
      if (!expenseByCategory[t.category]) {
        expenseByCategory[t.category] = 0;
      }
      expenseByCategory[t.category] += t.amount;
    });
  
  // 按金额排序
  const sortedCategories = Object.entries(expenseByCategory)
    .sort(([, a], [, b]) => b - a)
    .map(([categoryId, amount]) => ({
      category: getCategoryName(categoryId),
      amount
    }));
  
  return {
    columns: ['分类', '金额'],
    rows: sortedCategories
  };
});

const categoryBarOptions = {
  xAxis: {
    type: 'category',
    label: {
      autoHide: true,
      rotate: 45
    }
  },
  yAxis: {
    label: {
      formatter: (v: number) => '¥' + v
    }
  },
  tooltip: {
    formatter: (datum: any) => {
      return {
        name: datum.name,
        value: '¥' + datum.value.toLocaleString('zh-CN')
      };
    }
  }
};

// 趋势分析数据
const trendLineData = computed(() => {
  // 获取过去6个月的数据
  const now = new Date();
  const months: string[] = [];
  const monthlyData: Record<string, { income: number; expense: number }> = {};
  
  for (let i = 5; i >= 0; i--) {
    const month = new Date(now.getFullYear(), now.getMonth() - i, 1);
    const monthKey = `${month.getFullYear()}-${String(month.getMonth() + 1).padStart(2, '0')}`;
    months.push(monthKey);
    monthlyData[monthKey] = { income: 0, expense: 0 };
  }
  
  // 填充数据
  financeStore.transactions.forEach(t => {
    const date = new Date(t.date);
    const monthKey = `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}`;
    
    if (monthlyData[monthKey]) {
      if (t.type === 'income') {
        monthlyData[monthKey].income += t.amount;
      } else {
        monthlyData[monthKey].expense += t.amount;
      }
    }
  });
  
  return {
    columns: ['月份', '收入', '支出'],
    rows: months.map(month => ({
      '月份': month,
      '收入': monthlyData[month].income,
      '支出': monthlyData[month].expense
    }))
  };
});

const trendLineOptions = {
  legend: {
    position: 'top'
  },
  xAxis: {
    label: {
      autoHide: true
    }
  },
  yAxis: {
    label: {
      formatter: (v: number) => '¥' + v
    }
  },
  tooltip: {
    formatter: (datum: any) => {
      return {
        name: datum.name,
        value: '¥' + datum.value.toLocaleString('zh-CN')
      };
    }
  }
};

const expenseTrendData = computed(() => {
  // 获取过去6个月的支出趋势
  const now = new Date();
  const months: string[] = [];
  const monthlyData: Record<string, number> = {};
  
  for (let i = 5; i >= 0; i--) {
    const month = new Date(now.getFullYear(), now.getMonth() - i, 1);
    const monthKey = `${month.getFullYear()}-${String(month.getMonth() + 1).padStart(2, '0')}`;
    months.push(monthKey);
    monthlyData[monthKey] = 0;
  }
  
  // 填充数据
  financeStore.transactions
    .filter(t => t.type === 'expense')
    .forEach(t => {
      const date = new Date(t.date);
      const monthKey = `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}`;
      
      if (monthlyData[monthKey]) {
        monthlyData[monthKey] += t.amount;
      }
    });
  
  return {
    columns: ['月份', '支出'],
    rows: months.map(month => ({
      '月份': month,
      '支出': monthlyData[month]
    }))
  };
});

const expenseTrendOptions = {
  xAxis: {
    label: {
      autoHide: true
    }
  },
  yAxis: {
    label: {
      formatter: (v: number) => '¥' + v
    }
  },
  tooltip: {
    formatter: (datum: any) => {
      return {
        name: datum.name,
        value: '¥' + datum.value.toLocaleString('zh-CN')
      };
    }
  }
};

const incomeTrendData = computed(() => {
  // 获取过去6个月的收入趋势
  const now = new Date();
  const months: string[] = [];
  const monthlyData: Record<string, number> = {};
  
  for (let i = 5; i >= 0; i--) {
    const month = new Date(now.getFullYear(), now.getMonth() - i, 1);
    const monthKey = `${month.getFullYear()}-${String(month.getMonth() + 1).padStart(2, '0')}`;
    months.push(monthKey);
    monthlyData[monthKey] = 0;
  }
  
  // 填充数据
  financeStore.transactions
    .filter(t => t.type === 'income')
    .forEach(t => {
      const date = new Date(t.date);
      const monthKey = `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}`;
      
      if (monthlyData[monthKey]) {
        monthlyData[monthKey] += t.amount;
      }
    });
  
  return {
    columns: ['月份', '收入'],
    rows: months.map(month => ({
      '月份': month,
      '收入': monthlyData[month]
    }))
  };
});

const incomeTrendOptions = {
  xAxis: {
    label: {
      autoHide: true
    }
  },
  yAxis: {
    label: {
      formatter: (v: number) => '¥' + v
    }
  },
  tooltip: {
    formatter: (datum: any) => {
      return {
        name: datum.name,
        value: '¥' + datum.value.toLocaleString('zh-CN')
      };
    }
  }
};

// 详细数据表格配置
const detailColumns = [
  {
    title: '类型',
    dataIndex: 'type',
    key: 'type',
    width: 100,
    render: (type: string) => type === 'income' ? '收入' : '支出'
  },
  {
    title: '分类',
    dataIndex: 'category',
    key: 'category',
    width: 120
  },
  {
    title: '金额',
    dataIndex: 'amount',
    key: 'amount',
    width: 120
  },
  {
    title: '占比',
    dataIndex: 'percentage',
    key: 'percentage',
    width: 100
  }
];

const detailData = computed(() => {
  if (reportType.value === 'category') {
    // 分类报表详细数据
    const expenseByCategory: Record<string, number> = {};
    const totalExpense = periodTransactions.value
      .filter(t => t.type === 'expense')
      .reduce((sum, t) => sum + t.amount, 0);
    
    periodTransactions.value
      .filter(t => t.type === 'expense')
      .forEach(t => {
        if (!expenseByCategory[t.category]) {
          expenseByCategory[t.category] = 0;
        }
        expenseByCategory[t.category] += t.amount;
      });
    
    return Object.entries(expenseByCategory)
      .sort(([, a], [, b]) => b - a)
      .map(([categoryId, amount]) => ({
        type: 'expense',
        category: getCategoryName(categoryId),
        amount,
        percentage: totalExpense > 0 ? Math.round((amount / totalExpense) * 100) : 0
      }));
  } else if (reportType.value === 'monthly') {
    // 月度报表详细数据
    const monthlyData: Record<string, { income: number; expense: number }> = {};
    const totalIncome = periodTransactions.value
      .filter(t => t.type === 'income')
      .reduce((sum, t) => sum + t.amount, 0);
    const totalExpense = periodTransactions.value
      .filter(t => t.type === 'expense')
      .reduce((sum, t) => sum + t.amount, 0);
    
    periodTransactions.value.forEach(t => {
      const date = new Date(t.date);
      const monthKey = `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}`;
      
      if (!monthlyData[monthKey]) {
        monthlyData[monthKey] = { income: 0, expense: 0 };
      }
      
      if (t.type === 'income') {
        monthlyData[monthKey].income += t.amount;
      } else {
        monthlyData[monthKey].expense += t.amount;
      }
    });
    
    const result: any[] = [];
    Object.entries(monthlyData).forEach(([month, data]) => {
      result.push({
        type: 'income',
        category: month,
        amount: data.income,
        percentage: totalIncome > 0 ? Math.round((data.income / totalIncome) * 100) : 0
      });
      result.push({
        type: 'expense',
        category: month,
        amount: data.expense,
        percentage: totalExpense > 0 ? Math.round((data.expense / totalExpense) * 100) : 0
      });
    });
    
    return result.sort((a, b) => b.amount - a.amount);
  } else {
    // 趋势分析详细数据
    return [];
  }
});

const detailPagination = {
  pageSize: 10,
  showSizeChanger: true,
  showQuickJumper: true,
  showTotal: (total: number) => `共 ${total} 条记录`
};

// 组件挂载时初始化数据
onMounted(() => {
  financeStore.loadFromLocalStorage();
  if (financeStore.transactions.length === 0) {
    financeStore.initMockData();
  }
});
</script>

<style scoped>
.reports-container {
  padding: 24px;
}

.reports-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 24px;
  flex-wrap: wrap;
  gap: 16px;
}

.reports-header h1 {
  font-size: 24px;
  margin: 0;
}

.header-controls {
  display: flex;
  gap: 12px;
  align-items: center;
  flex-wrap: wrap;
}

.report-type-select,
.period-select {
  width: 180px;
}

.overview-section {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
  gap: 16px;
  margin-bottom: 24px;
}

.overview-card {
  background-color: var(--color-bg-2);
  border-radius: 8px;
  padding: 16px;
  text-align: center;
}

.overview-title {
  font-size: 14px;
  color: var(--color-text-secondary);
  margin-bottom: 8px;
}

.overview-value {
  font-size: 24px;
  font-weight: 600;
  margin-bottom: 4px;
}

.overview-value.income {
  color: var(--color-success);
}

.overview-value.expense {
  color: var(--color-danger);
}

.overview-value.balance {
  color: var(--color-info);
}

.overview-value.ratio {
  color: var(--color-warning);
}

.overview-change {
  font-size: 12px;
}

.overview-change.positive {
  color: var(--color-success);
}

.overview-change.negative {
  color: var(--color-danger);
}

.overview-hint {
  font-size: 12px;
  color: var(--color-text-secondary);
}

.charts-section {
  margin-bottom: 24px;
}

.chart-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(400px, 1fr));
  gap: 24px;
}

.chart-card {
  background-color: var(--color-bg-2);
  border-radius: 8px;
  padding: 20px;
}

.chart-card.full-width {
  grid-column: 1 / -1;
}

.chart-card h3 {
  font-size: 18px;
  margin: 0 0 16px 0;
}

.chart-container {
  height: 300px;
}

.details-section {
  background-color: var(--color-bg-2);
  border-radius: 8px;
  padding: 20px;
}

.section-header {
  margin-bottom: 16px;
}

.section-header h3 {
  font-size: 18px;
  margin: 0;
}

.details-table :deep(.arco-table-cell) {
  vertical-align: middle;
}

.details-table :deep(.arco-table-cell.amount .income) {
  color: var(--color-success);
  font-weight: 600;
}

.details-table :deep(.arco-table-cell.amount .expense) {
  color: var(--color-danger);
  font-weight: 600;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .reports-header {
    flex-direction: column;
    align-items: stretch;
  }
  
  .header-controls {
    flex-direction: column;
    align-items: stretch;
  }
  
  .report-type-select,
  .period-select {
    width: 100%;
  }
  
  .overview-section {
    grid-template-columns: 1fr;
  }
  
  .chart-grid {
    grid-template-columns: 1fr;
  }
  
  .chart-container {
    height: 250px;
  }
  
  .chart-card.full-width {
    grid-column: auto;
  }
}
</style>